package com.youpai.platform.chat.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youpai.platform.chat.service.entity.dto.OfflineEventDTO;
import com.youpai.platform.chat.service.entity.dto.OnlineEventDTO;
import com.youpai.platform.chat.service.entity.po.ChatAccountPO;
import com.youpai.platform.chat.service.mapper.ChatAccountMapper;
import com.youpai.platform.chat.service.service.VultureChatEventFacadeInterface;
import com.youpai.platform.chat.service.util.ChatUtils;
import com.youpai.platform.user.service.biz.UserActiveBizService;
import com.youpai.platform.user.service.entity.dto.UserStateChangedDTO;
import com.youpai.platform.user.service.enums.UserStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @date: 2022/7/16 21:04
 * @author: Anna
 * @version: 1.0
 * @description: vultureChat事件门面
 */
@Slf4j
@Component
public class VultureChatEventFacadeImpl implements VultureChatEventFacadeInterface {

    @Resource
    private UserActiveBizService userActiveBizService;

    @Resource
    private ChatAccountMapper chatAccountMapper;

    @Override
    public void onlineEvent(OnlineEventDTO onlineEventDTO) {
        log.info("{} - 上线了", onlineEventDTO.getAccId());
        sendUserStateChangeEvent(onlineEventDTO.getAccId(), UserStateEnum.ONLINE);
    }

    @Override
    public void offlineEvent(OfflineEventDTO offlineEventDTO) {
        log.info("{} - 下线了", offlineEventDTO.getAccId());
        sendUserStateChangeEvent(offlineEventDTO.getAccId(), UserStateEnum.OFFLINE);
    }

    private void sendUserStateChangeEvent(String accId, UserStateEnum userStateEnum) {
        String uid = ChatUtils.getUidByAccId(accId);
        LambdaQueryWrapper<ChatAccountPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatAccountPO::getAccId,accId);
        final ChatAccountPO chatAccountPO = chatAccountMapper.selectOne(queryWrapper);
        if(null == chatAccountPO){
            // 未知accId
            return;
        }
        UserStateChangedDTO userStateChangedDTO = new UserStateChangedDTO();
        userStateChangedDTO.setTimeStamp(System.currentTimeMillis())
                .setUid(Long.parseLong(uid))
                .setUserState(userStateEnum.state);
        userActiveBizService.userStateChanged(userStateChangedDTO);
    }
}
